package com.maosy.demo

import android.content.Context
import android.content.Intent
import com.maosy.demo.channel.DemoMethodChannel
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MyFlutterActivity : FlutterActivity() {


    override fun getInitialRoute(): String? {
        return if (intent.getStringExtra(CACHED_ENGINE_ID) == null) super.getInitialRoute() else intent.getStringExtra(
            CACHED_ENGINE_ID
        )
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        val methodChannel =
            MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL_NAME)
        methodChannel.setMethodCallHandler { call, result ->
            DemoMethodChannel.optionCall(methodChannel, call, result, context)
        }
    }

    companion object {
        const val CACHED_ENGINE_ID = "cached_engine_id"
        const val CHANNEL_NAME = "com.maosy.demo.method/channel"

        @JvmStatic
        fun start(context: Context, cachedEngineId: String) {
            val intent = Intent(context, MyFlutterActivity::class.java)
            intent.putExtra(CACHED_ENGINE_ID, cachedEngineId)
            context.startActivity(intent)
        }
    }
}